package com.sunyard.manage.controller;

import com.sunyard.constant.manage.CommonConst;
import com.sunyard.dal.dto.PopedomAddReqDTO;
import com.sunyard.dal.entity.Popedom;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.manage.helper.PopedomHelper;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.manage.service.PopedomService;
import com.sunyard.redisUtil.RedisUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author jiy.fang
 * @Description description
 * @date 2019/7/10
 */
@Api(tags = "PopedomController", description = "权限Controller")
@Slf4j
@RestController
@RequestMapping("/popedom")
public class PopedomController {

    @Autowired
    private PopedomService popedomService;

    /**
     * @return String
     * @Description:获取当前用户的权限
     */
    @RequestMapping(value = "/findPopedoms", method = RequestMethod.POST)
    public BaseResult findPopedoms(HttpServletRequest request, HttpServletResponse response) {
        try {
            String roleId = TokenUtil.getRoleId(request.getHeader("token"));
            List<Popedom> popedoms = (List<Popedom>) RedisUtil.get("popedom:loginOperator:" + roleId);
            if (popedoms != null) {
                //先返回一个一级菜单
                List<Popedom> allTree = PopedomHelper.getAllTree(popedoms);
                return GetResult.getResult(allTree);
            }
            return GetResult.getResultCodeAndMessage(CommonConst.NO_POPEDOM, "获取权限信息失败,请重新登录!");
        } catch (Exception e) {
            log.error("系统异常", e);
            return GetResult.getResultCodeAndMessage(CommonConst.NO_POPEDOM, "获取权限信息失败,请重新登录!");
        }
    }

    @ApiOperation(value = "新增权限")
    @PostMapping(value = "/addPopedom")
    public BaseResult addPopedom(@RequestBody PopedomAddReqDTO addReqDTO) {
        try {
            return popedomService.addPopedom(addReqDTO);
        } catch (Exception e) {
            log.error("新增菜单错误", e);
            return GetResult.getResultFail(e.getMessage());
        }
    }

}
